﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Xml.Linq;

namespace SCFHS.Shared
{
    public partial class Attachments : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                BindfrmAttachments();

            string AttachmentID = Request.QueryString["AttachmentID"];
            if (!string.IsNullOrEmpty(AttachmentID))
            {
                DataTable dt = ((DataTable)frmvAttachmentsImages.DataSource);
                DataRow dr = dt.Select("img_id = " + AttachmentID).First();
                if (dr != null)
                    frmvAttachmentsImages.PageIndex = dt.Rows.IndexOf(dr) < frmvAttachmentsImages.PageCount ? dt.Rows.IndexOf(dr) : 0;
                BindfrmAttachments();
            }
        }

        void BindfrmAttachments(bool withIndexing = false)
        {
            DataTable dt = new DataTable();
            XDocument doc = XDocument.Load(Server.MapPath("Storage.xml"));
            if (doc != null)
            {
                XElement[] items = doc.Root.Elements("Item").ToArray();

                dt.Columns.Add("img_id");
                dt.Columns.Add("img_description");
                DataRow dr;
                foreach (XElement element in items)
                {
                    dr = dt.NewRow();
                    dr["img_id"] = element.Attribute("ID").Value;
                    dr["img_description"] = element.Element("discription").Value;
                    dt.Rows.Add(dr);
                }
            }
            frmvAttachmentsImages.DataSource = dt;
            frmvAttachmentsImages.DataBind();
        }

        public string GetImage(string img_ID)
        {
            return ("GetImages.aspx?imgID=" + img_ID);
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {

        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                XDocument doc = XDocument.Load(Server.MapPath("Storage.xml"));
                if (doc != null)
                {
                    XElement elemnt = doc.Root.Elements().Where(ele => ele.Attribute("ID").Value == ((Button)sender).CommandArgument).First();
                    elemnt.Element("discription").Value = hdfTxtToSave.Value;
                }
                doc.Save(Server.MapPath("Storage.xml"));
                BindfrmAttachments();
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        protected void frmvAttachmentsImages_PageIndexChanging(object sender, FormViewPageEventArgs e)
        {
            frmvAttachmentsImages.PageIndex = e.NewPageIndex;
            BindfrmAttachments();
        }


    }
}